package lihua.robot.utils;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lihua.robot.controller.BlocksController;
import lihua.robot.pojo.Device;
import lihua.robot.pojo.ExpiredOrders;
import lihua.robot.service.DeviceService;
import lihua.robot.service.ExpiredOrdersService;
import lihua.robot.service.FallingTimeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static lihua.robot.utils.RedisUtil.getWarehouselocation;
import static lihua.robot.utils.TransportationConditionsUtil.determineTheHandoverArea;
import static lihua.robot.utils.TransportationConditionsUtil.setKW0;

@Component
public class DetectOrdersUtil {

    private static final Logger logger = LoggerFactory.getLogger(DetectOrdersUtil.class);
    public static void restoreOrders() {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
        FallingTimeService fallingTimeService = (FallingTimeService) ApplicationContextUtil.getBean(FallingTimeService.class);
        BlocksController blocksController = new BlocksController();
        DeviceService deviceService = (DeviceService)ApplicationContextUtil.getBean(DeviceService.class);

        ExpiredOrdersService expiredOrdersService = (ExpiredOrdersService)ApplicationContextUtil.getBean(ExpiredOrdersService.class);
        String devSn = expiredOrdersService.detectOrders();
        int devsn = Integer.parseInt(devSn);
        if(expiredOrdersService.detectOrders()!=null){

            if(getWarehouselocation(3,determineTheHandoverArea(devsn)) == null ||
                    getWarehouselocation(1,determineTheHandoverArea(devsn))== null ||
                    getWarehouselocation(2,determineTheHandoverArea(devsn)) == null ||
                    getWarehouselocation(4,determineTheHandoverArea(devsn)) == null
            ){
                logger.info("暂无合适库位");
            }
            else {
                LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Device::getWorkshop,3)
                        .eq(Device::getDevsn,devSn);
                Device de = deviceService.getBaseMapper().selectOne(wrapper);
                //小桶运单1
                executorService.schedule(() -> {
                    System.out.println("设备"+devSn+"--"+DateUtil.date()+"AMB-0302-开始执行-1");

                    String XMAP = getWarehouselocation(3,determineTheHandoverArea(devsn));
                    System.out.println(XMAP);
                    String xydid = String.valueOf(blocksController.s_transportFullBarrels(devsn, XMAP).getData());
                    //订单接收预约情况置为1
                    RedisUtil.setKW1(XMAP);
                    fallingTimeService.saveFallingTime(0, 0, devsn, 3, xydid, 1, 0);
                    // 订单完成后预约情况置为0
                    try {
                        setKW0(XMAP,xydid);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }

                }, 15, TimeUnit.MINUTES);

                // 大桶运单1
                executorService.schedule(() -> {
                    de.setState(2);
                    de.setUpdateTime(DateUtil.date());
                    deviceService.getBaseMapper().updateById(de);

                    System.out.println("设备"+devSn+"--"+DateUtil.date()+"AMB-0301-开始执行-1");
                    String MAP = getWarehouselocation(1,determineTheHandoverArea(devsn));
                    System.out.println(MAP);
                    String ydid = String.valueOf(blocksController.transportFullBarrels(String.valueOf(devsn),MAP).getData());
                    RedisUtil.setKW1(MAP);
                    fallingTimeService.saveFallingTime(0, 0, devsn, 3, ydid, 0, null);
                    try {
                        setKW0(MAP,ydid);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }, 30, TimeUnit.MINUTES);

                // 大桶运单2
                executorService.schedule(() -> {

                    System.out.println("设备"+devSn+"--"+DateUtil.date()+"AMB-0301-开始执行-2");
                    String KAP = getWarehouselocation(2,determineTheHandoverArea(devsn));
                    System.out.println(KAP);
                    String ydid = String.valueOf(blocksController.transportEmptyDrums(String.valueOf(devsn), KAP).getData());
                    RedisUtil.setKW1(KAP);
                    fallingTimeService.saveFallingTime(0, 0, devsn, 3, ydid, 0, null);
                    try {
                        setKW0(KAP,ydid);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }, 32, TimeUnit.MINUTES);


                //小桶运单2
                executorService.schedule(() -> {
                    System.out.println("设备"+devSn+"--"+DateUtil.date()+"AMB-0302-开始执行-2");

                    String XKAP = getWarehouselocation(4,determineTheHandoverArea(devsn));
                    System.out.println(XKAP);
                    String xydid = String.valueOf(blocksController.s_transportEmptyDrums(devsn, XKAP).getData());
                    RedisUtil.setKW1(XKAP);
                    fallingTimeService.saveFallingTime(0, 0, devsn, 3, xydid, 1, 0);
                    try {
                        setKW0(XKAP,xydid);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }

                }, 35, TimeUnit.MINUTES);
                LambdaQueryWrapper<ExpiredOrders> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(ExpiredOrders::getDesvn,devSn);
                expiredOrdersService.remove(wrapper1);
            }
        }
    }


    public static void runDetectOrder() {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5); // 创建一个拥有5个线程的线程池
        Runnable task = () -> {
            restoreOrders();
        };
        // 延迟0秒后开始执行任务，每隔1秒执行一次
        executorService.scheduleAtFixedRate(task, 0, 5, TimeUnit.MINUTES);
    }
}
